﻿using System.Text;

namespace TPXSDK.NET.Mission.Instruction;

internal class InstWaitClimb : Tokenizer
{
    public InstWaitClimb(TokenizerAdmin admin)
    {
        Admin = admin;
        KeyName = "waitclimb";
        KeyValue = (byte)FlyCmdId.CMD_WAITCLIMB;
        Usage = "waitclimb alt";
        Description = @"Waits until a climb, initialized by the climb command, has reached the altitude specified in the altitude parameter.";
    }

    public override bool Process()
    {
        var flyCmp = Admin?.Compiler; if (null == flyCmp) return false;
        var tokens = flyCmp.GetLineTokens();
        if (null == tokens || (tokens.Count != 2 && tokens.Count != 3))
        {
            flyCmp.ErrorMsg = $"{KeyName} Invalid Usage";
            return false;
        }

        var cmd = new FlyCmdItem
        {
            Id = (byte)KeyValue,
            LineNum = tokens[0].Row
        };
        tokens.RemoveAt(0);// Remove Flycmd Name

        var altKind = ParaType.REL_POS;//默认相对高度
        if (tokens.Count == 2 && tokens[1].Type == TokenType.NUMBER)
        {
            if (Convert.ToInt32(tokens[1].Name) == 1)
            {
                altKind = ParaType.ABS_POS;// 海拔高度
            }
        }

        if (tokens[0].Type == TokenType.NUMBER)
        {
            cmd.P1 = (byte)altKind;
            cmd.P3.FloatVal = Convert.ToSingle(tokens[0].Name);
            flyCmp.CmdList.Add(cmd);
            return true;
        }

        flyCmp.ErrorMsg = $"{KeyName} Invalid param";
        return false;
    }

    public override void Reverse(FlyCmdItem cmd, StringBuilder sb)
    {
        if (cmd.P1 == (byte)ParaType.ABS_POS)
        {
            sb.AppendLine($"{KeyName} {cmd.P3.FloatVal.ToString("0.##")} 1 //m ABS");
        }
        else
        {
            sb.AppendLine($"{KeyName} {cmd.P3.FloatVal.ToString("0.##")}//m");
        }
    }
}
